﻿/*
 * Copyright (c) 2011, The Chancellor, Masters and Scholars of the University of Oxford
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are 
 * permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this list of 
 *   conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice, this list 
 *   of conditions and the following disclaimer in the documentation and/or other 
 *   materials provided with the distribution.
 *
 * Neither the name of University of Oxford nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior 
 * written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using System.Xml.Linq;
using Vreci.Metadata.Annotation;
using System.ComponentModel;
using Vreci.Metadata.Dicom.Silverlight;
using System.Text;
using System.Diagnostics;

namespace FileManager
{
    public partial class MainPage : UserControl, INotifyPropertyChanged
    {
        #region Properties

        private XNamespace xmnnsProps = "http://vreci/properties/1/";

        public VreciProperties GroupMetadata
        {
            get;
            set;
        }

        public VreciProperties CurrentDCMMetadata
        {
            get;
            set;
        }

        public ClientContext ClientCtx
        {
            get;
            set;
        }

        public List DCMList
        {
            get;
            set;
        }

        public List ShadowList
        {
            get;
            set;
        }

        public string DCMLibrary
        {
            get;
            set;
        }

        public string CleanDCMLibrary
        {
            get
            {
                return HttpUtility.UrlDecode(DCMLibrary);
            }
          
        }

        public ListItemCollection DCMListItems
        {
            get;
            set;
        }

        public ListItemCollection ShadowListItems
        {
            get;
            set;
        }

        public ObservableCollection<string> DCMFilenames
        {
            get;
            set;
        }

        #endregion
        
        public MainPage()
        {
            InitializeComponent();
            DCMFilenames = new ObservableCollection<string>();
            FileDetails.ItemsSource = DCMFilenames;
            GroupMetadata = new VreciProperties();
            DataContext = this;
            Unloaded += new RoutedEventHandler(MainPage_Unloaded);

        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            if (FileDetails.SelectedIndex > -1) SaveMetadata(FileDetails.SelectedValue + "/curated_metadata.xml");
            if (FileDetails.SelectedIndex > -1) SaveAnnotation(FileDetails.SelectedValue + "/curated_annotation.xml");
 
        }

        public MainPage(string DCMLibraryPath)
        {
            DCMLibrary = DCMLibraryPath;
            InitializeComponent();
            DCMFilenames = new ObservableCollection<string>();
            FileDetails.ItemsSource = DCMFilenames;
            GroupMetadata = new VreciProperties();
            DataContext = this;
        }
        
        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            ClientCtx = new ClientContext(ApplicationContext.Current.Url + @"/");

            string UrlPath = HttpUtility.UrlDecode(DCMLibrary);

            ShadowList = ClientCtx.Web.Lists.GetByTitle(@"Shadow Document Library");

            DCMList = ClientCtx.Web.Lists.GetByTitle(UrlPath);

            GetShadowDocLib();

            //FillFileList();
        }

        private void GetShadowDocLib()
        {
            ShadowList = ClientCtx.Web.Lists.GetByTitle(@"Shadow Document Library");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.FolderServerRelativeUrl = @"/" + DCMLibrary;
            ShadowListItems = ShadowList.GetItems(camlQuery);

            ClientCtx.Load(ShadowListItems,
                  items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.FileSystemObjectType,
                    item => item.File
                    ));

            ClientCtx.ExecuteQueryAsync(LoadShadowSiteData, FailLoadSiteData);
        }

        private void LoadShadowSiteData(object Sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        try
                        {
                            foreach (var d in ShadowListItems)
                            {
                                try
                                {
                                    if (d.FileSystemObjectType == FileSystemObjectType.Folder && d.DisplayName.EndsWith(".dcm"))
                                    {
                                        DCMFilenames.Add(d.DisplayName);
                                    }
                                    if (d.FileSystemObjectType == FileSystemObjectType.File && d.File.Name == "curated.group.metadata.xml")
                                    {
                                        string[] ss = d.File.ServerRelativeUrl.Split('/');

                                        string parentDirectoryName = ss[ss.Count() - 2];

                                        if (parentDirectoryName == DCMLibrary)
                                        {
                                            Microsoft.SharePoint.Client.File.OpenBinaryDirect(ClientCtx, d.File.ServerRelativeUrl, LoadGroupFileSucceed, LoadGroupFileFailed);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButton.OK);
                                }
                            }
                            FileDetails.ItemsSource = null;
                            FileDetails.ItemsSource = DCMFilenames.Distinct().OrderBy(i => i);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButton.OK);
                        }
                    }
                )
            );
        }
/*
        private void FillFileList()
        {
            CamlQuery camlQuery = new CamlQuery();
            DCMListItems = DCMList.GetItems(camlQuery);
            ClientCtx.Load(DCMListItems,
                  items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.File).Where(item => item.FileSystemObjectType == FileSystemObjectType.File)); //Make sure the returned ListItem are "File" type

            ClientCtx.ExecuteQueryAsync(LoadSiteData, FailLoadSiteData);
        }
*/
        private void FailLoadSiteData(object sender, ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        MessageBox.Show(e.Message);
                    }
                )
            );
        }
/*        
        private void LoadSiteData(object Sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        try
                        {
                            if (DCMFilenames == null)
                            {
                                DCMFilenames = new ObservableCollection<string>();
                            }
                            foreach (var d in DCMListItems)
                            {
                                try
                                {
                                    //if (!d.File.Name.StartsWith("curated.") && !d.File.Name.StartsWith("filter."))
                                    //{
                                    //    DCMFilenames.Add(d.File.Name.Split('.')[0]);
                                    //}
                                    if (d.File.Name == "curated.group.metadata.xml")
                                    {
                                        Microsoft.SharePoint.Client.File.OpenBinaryDirect(ClientCtx, d.File.ServerRelativeUrl, LoadGroupFileSucceed, LoadGroupFileFailed);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButton.OK);
                                }
                            }
                            FileDetails.ItemsSource = null;
                            FileDetails.ItemsSource = DCMFilenames.Distinct().OrderBy(i => i);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButton.OK);
                        }
                    }
                )
            );
        }
*/
        private void FileDetails_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
                Microsoft.SharePoint.Client.File clFileToUpload = null;
                foreach (var fi in files)
                {
                    var fciFileToUpload = new FileCreationInformation();
                    using (Stream streamToUpload = fi.OpenRead())
                    {
                        int length = (int)streamToUpload.Length;  // get file length
                        fciFileToUpload.Content = new byte[length];
                        int count = 0;                        // actual number of bytes read
                        int sum = 0;                          // total number of bytes read
                        while ((count = streamToUpload.Read(fciFileToUpload.Content, sum, length - sum)) > 0)
                        {
                            sum += count;  // sum is a buffer offset for next reading
                        }
                    }
                    fciFileToUpload.Overwrite = true;
                    fciFileToUpload.Url = fi.Name;
                    clFileToUpload = DCMList.RootFolder.Files.Add(fciFileToUpload);

                    ClientCtx.Load(clFileToUpload);
                    ClientCtx.ExecuteQueryAsync(OnLoadingSucceeded, OnLoadingFailed);
                }
            }
        }

        private void OnLoadingSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        //FillFileList();
                        GetShadowDocLib();
                    }
                )
            );
        }

        private void OnLoadingFailed(object sender, ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        MessageBox.Show(e.Message);
                    }
                )
            );
        }

        private bool _EditedAnnotation = false;
        [DefaultValue(false)]
        public bool EditedAnnotation
        {
            get
            {
                return _EditedAnnotation;
            }
            set
            {
                _EditedAnnotation = true;
                OnPropertyChanged("EditedAnnotation");
            }
        }

        private bool _EditedMetadata = false;
        [DefaultValue(false)]
        public bool EditedMetadata
        {
            get
            {
                return _EditedMetadata;
            }
            set
            {
                _EditedMetadata = value;
                OnPropertyChanged("EditedMetadata");
            }
        }

        public string OldSelect
        {
            get;
            set;
        }
        private void FileDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DCMFilenames.Clear();
            imgAnnotator.Source = null;
            imgAnnotator.Strokes.Clear();
            dgDCMMetadata.ItemsSource = null;

            if (FileDetails.SelectedIndex < 0)
            {
                tabDCMDetails.IsEnabled = false;
                return;
            }
            else
            {
                tabDCMDetails.IsEnabled = true;
                //SaveMetadata(FileDetails.SelectedValue + ".curated.file.metadata.xml");
                //SaveAnnotation(FileDetails.SelectedValue + ".curated.file.annotation.xml");
            }

            //if ((EditedMetadata || EditedAnnotation) && e.RemovedItems.Count > 0)
            if (e.RemovedItems.Count > 0)
            {
                //MessageBoxResult r = MessageBox.Show("You have made changes to the DCM's metadata/annotation. Do you want to save the annotation before loading the next image?", "Warning", MessageBoxButton.OKCancel);
                //if (r == MessageBoxResult.OK)
                //{
                    //if (EditedMetadata) 
                        SaveMetadata(e.RemovedItems[0].ToString() + "/curated_metadata.xml");
                    //if (EditedAnnotation) 
                        SaveAnnotation(e.RemovedItems[0].ToString() + "/curated_annotation.xml");
                //}
            }

            foreach (var i in ShadowListItems)
            {
                if (i.FileSystemObjectType != FileSystemObjectType.File)
                {
                    continue;
                }

                if (i.File.ServerRelativeUrl.EndsWith(DCMLibrary + "/" + FileDetails.SelectedValue + "/curated_metadata.xml"))
                {
                    try
                    {
                        CurrentDCMMetadata = null;
                        Microsoft.SharePoint.Client.File.OpenBinaryDirect(ClientCtx, i.File.ServerRelativeUrl, LoadDCMMetadataFileSucceed, LoadDCMMetadataFileFailed);
                    }
                    catch (ClientRequestException cre)
                    {
                    }
                }

                if (i.File.ServerRelativeUrl.EndsWith(DCMLibrary + "/" + FileDetails.SelectedValue + "/DeepZoom/Frame_0/image.xml"))
                {
                    try
                    {
                        imgAnnotator.Source = new DeepZoomImageTileSource(new Uri(ClientCtx.Url + i.File.ServerRelativeUrl, UriKind.RelativeOrAbsolute));
                        imgAnnotator.ImageWidth = Convert.ToInt32(GroupMetadata.Properties.FirstOrDefault(li => li.Reference == "http://vreci/dimensions#width").Value);
                        imgAnnotator.ImageHeight = Convert.ToInt32(GroupMetadata.Properties.FirstOrDefault(li => li.Reference == "http://vreci/dimensions#height").Value);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                if (i.File.ServerRelativeUrl.EndsWith(DCMLibrary + "/" + FileDetails.SelectedValue + "/curated_annotation.xml"))
                {
                    Microsoft.SharePoint.Client.File.OpenBinaryDirect(ClientCtx, i.File.ServerRelativeUrl, LoadDCMAnnotationFileSucceed, LoadDCMAnnotationFileFailed);
                }

                EditedAnnotation = false;
                EditedMetadata = false;
            }
        }

        private void LoadGroupFileSucceed(object sender, OpenBinarySucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        XDocument doc = XDocument.Load(e.Stream);
                        GroupMetadata = new VreciProperties();
                        GroupMetadata.Read(doc);
                        dgGroupMetadata.ItemsSource = GroupMetadata.Properties.Where(i => i.Hidden == false);
                    }
                )
            );
        }

        private void LoadGroupFileFailed(object sender, OpenBinaryFailedEventArgs e)
        {
            MessageBox.Show("Failed to load group metadata", "Error", MessageBoxButton.OK);
        }

        private void LoadDCMMetadataFileSucceed(object sender, OpenBinarySucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        CurrentDCMMetadata = null;
                        XDocument doc = XDocument.Load(e.Stream);
                        CurrentDCMMetadata = new VreciProperties();
                        CurrentDCMMetadata.Read(doc);
                        dgDCMMetadata.ItemsSource = CurrentDCMMetadata.Properties.Where(i => i.Hidden == false);
                    }
                )
            );
        }

        private void LoadDCMMetadataFileFailed(object sender, OpenBinaryFailedEventArgs e)
        {
            MessageBox.Show("Failed to load DCM metadata", "Error", MessageBoxButton.OK);
        }

        private void LoadDCMAnnotationFileSucceed(object sender, OpenBinarySucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        XDocument doc = XDocument.Load(e.Stream);
                        imgAnnotator.Strokes.Clear();
                        imgAnnotator.Strokes = InkPresenterUtil.XmlToStrokes(doc);
                        if (imgAnnotator.Strokes.Count > 0)
                        {
                            btnClearAnnotate.IsEnabled = true;
                        }
                        else
                        {
                            btnClearAnnotate.IsEnabled = false;
                        }
                    }
                )
            );
        }

        private void LoadDCMAnnotationFileFailed(object sender, OpenBinaryFailedEventArgs e)
        {
            MessageBox.Show("Failed to load DCM annotation", "Error", MessageBoxButton.OK);
        }

        private void SaveMetadata(string metadatafile)
        {
            if (CurrentDCMMetadata == null) return;

            XDocument doc = CurrentDCMMetadata.Write();
            
            var fciFileToUpload = new FileCreationInformation();
            fciFileToUpload.Content = Encoding.UTF8.GetBytes(doc.ToString());
            fciFileToUpload.Overwrite = true;
            fciFileToUpload.Url = "/Hidden_Shadow/" + DCMLibrary + "/" + metadatafile;
            Microsoft.SharePoint.Client.File clFileToUpload = ShadowList.RootFolder.Files.Add(fciFileToUpload);

            ClientCtx.Load(clFileToUpload);

            ClientCtx.ExecuteQueryAsync(UpdateMetadataSucceed, UpdateMetadataFailed);
        }

        private void SaveAnnotation(string annotationfile)
        {
            //if (imgAnnotator.Strokes.Count == 0) return;
            if (!imgAnnotator.Annotating) return;
            //if (imgAnnotator.Annotating) return;
            XDocument doc = imgAnnotator.Strokes.ToXml();
            doc.Root.Add(new XAttribute("runtime_width", imgAnnotator.AnnotationLayer.Width));
            doc.Root.Add(new XAttribute("runtime_height", imgAnnotator.AnnotationLayer.Height));
            var fciFileToUpload = new FileCreationInformation();
            fciFileToUpload.Content = Encoding.UTF8.GetBytes(doc.ToString());
            fciFileToUpload.Overwrite = true;
            fciFileToUpload.Url = "/Hidden_Shadow/" + DCMLibrary + "/" + annotationfile;
            Microsoft.SharePoint.Client.File clFileToUpload = ShadowList.RootFolder.Files.Add(fciFileToUpload);

            ClientCtx.Load(clFileToUpload);

            ClientCtx.ExecuteQueryAsync(UpdateAnnotationSucceed, UpdateAnnotationFailed);
        }

        private void imgAnnotator_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            EditedAnnotation = true;
            SaveAnnotation(FileDetails.SelectedValue + "/curated_annotation.xml");
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }



        private void btnRefreshFileList_Click(object sender, RoutedEventArgs e)
        {

            GetShadowDocLib();
            //FillFileList();
        }

        private void btnSaveGroupMetadata_Click(object sender, RoutedEventArgs e)
        {
            XDocument doc = GroupMetadata.Write();
            ListItem group = ShadowListItems.ToList().DefaultIfEmpty(null).FirstOrDefault(i => i.FileSystemObjectType == FileSystemObjectType.File && i.File.Name == "curated.group.metadata.xml");//
            //var fciFileToUpload = new FileCreationInformation();
            //fciFileToUpload.Content = Encoding.UTF8.GetBytes(doc.ToString());
            //fciFileToUpload.Overwrite = true;
            //fciFileToUpload.Url = "curated.group.metadata.xml";
            //Microsoft.SharePoint.Client.File clFileToUpload = group.ParentList.RootFolder.Files.Add(fciFileToUpload);
            FileSaveBinaryInformation fff = new FileSaveBinaryInformation();
            fff.Content = Encoding.UTF8.GetBytes(doc.ToString());
            try
            {
                group.File.SaveBinary(fff);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //ClientCtx.Load(clFileToUpload);

            //ClientCtx.ExecuteQueryAsync(UpdateGroupSucceed, UpdateGroupFailed);
        }

        private void UpdateGroupSucceed(object o, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        //MessageBox.Show("Group metadata saved");
                    }
                )
            );
        }

        private void UpdateGroupFailed(object o, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show(e.Message);
        }

        private void UpdateMetadataSucceed(object o, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        //MessageBox.Show("Metadata saved");
                        EditedMetadata = false;
                    }
                )
            );
        }

        private void UpdateMetadataFailed(object o, ClientRequestFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        MessageBox.Show(e.Message);
                        
                    }
                )
            );
        }

        private void UpdateAnnotationSucceed(object o, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(
                new Action(
                    delegate()
                    {
                        //MessageBox.Show("Annotation saved");
                        EditedAnnotation = false;
                    }
                )
            );
        }

        private void UpdateAnnotationFailed(object o, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show(e.Message);
        }

        public ListItemCollection tempListItems
        {
            get;
            set;
        }

        private void btnReloadGroupMetadata_Click(object sender, RoutedEventArgs e)
        {
            //FillFileList();
            GetShadowDocLib();
        }

        private void btnSaveMetadata_Click(object sender, RoutedEventArgs e)
        {
            //SaveMetadata(FileDetails.SelectedValue + ".curated.file.metadata.xml");
            SaveMetadata(FileDetails.SelectedValue + "/curated_metadata.xml");
        }

        private void btnSaveAnnotation_Click(object sender, RoutedEventArgs e)
        {
            SaveAnnotation(FileDetails.SelectedValue + "/curated_annotation.xml");
        }

        private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            EditedMetadata = true;
        }

        private void dgGroupMetadata_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
        {
            XDocument doc = GroupMetadata.Write();
            ListItem group = ShadowListItems.ToList().DefaultIfEmpty(null).FirstOrDefault(i => i.FileSystemObjectType == FileSystemObjectType.File && i.File.Name == "curated.group.metadata.xml");
            //var fciFileToUpload = new FileCreationInformation();
            //fciFileToUpload.Content = Encoding.UTF8.GetBytes(doc.ToString());
            //fciFileToUpload.Overwrite = true;
            //fciFileToUpload.Url = group.File + "/curated.group.metadata.xml";
            //Microsoft.SharePoint.Client.File clFileToUpload = group.ParentList.RootFolder.Files.Add(fciFileToUpload);
            FileSaveBinaryInformation fff = new FileSaveBinaryInformation();
            fff.Content = Encoding.UTF8.GetBytes(doc.ToString());
            try
            {
                group.File.SaveBinary(fff);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //ClientCtx.Load(clFileToUpload);

            //ClientCtx.ExecuteQueryAsync(UpdateGroupSucceed, UpdateGroupFailed);
        }

        private void dgDCMMetadata_CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
        {
            //SaveMetadata(FileDetails.SelectedValue + "/curated_metadata.xml");
        }

        private void btnEditAnnotate_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnClearAnnotate_Click(object sender, RoutedEventArgs e)
        {
            imgAnnotator.Strokes.Clear();
            SaveAnnotation(FileDetails.SelectedValue + "/curated_annotation.xml");
            btnClearAnnotate.IsEnabled = false;
        }

        private void btnAnnotate_Click(object sender, RoutedEventArgs e)
        {
            if (btnAnnotate.IsChecked == true)
            {
                //btnAnnotate.Foreground = new SolidColorBrush()
                //{
                //    Color = Colors.Blue
                //};
                btnAnnotate.Content = "Annotation Enabled";
                //btnClearAnnotate.Visibility = System.Windows.Visibility.Visible;
                imgAnnotator.Annotating = true;
            }
            else
            {
                //btnAnnotate.Foreground = new SolidColorBrush()
                //{
                //    Color = Colors.Blue
                //};
                btnAnnotate.Content = "Annotation Disabled";
                //btnClearAnnotate.Visibility = System.Windows.Visibility.Collapsed;
                imgAnnotator.Annotating = false;
            }
        }

        private void dgDCMMetadata_LostFocus(object sender, RoutedEventArgs e)
        {
            //SaveMetadata("curated_metadata.xml");
        }
    }
}
